package com.sdd.sndd;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.List;

/**
 * ClassName: NacosConfigDemo
 * Description:
 * date: 2020/7/1
 *
 * @author xugaojun
 */
public class NacosConfigDemo {

    private static final String KEY = "TestResource";
    // nacos server ip
    private static final String remoteAddress = "youraddress";
    // nacos group
    private static final String groupId = "Sentinel:Nacos-Demo";
    // nacos dataId
    private static final String dataId = "com.sdd.sndd";

    public static void main(String[] args) {
        initRules();
        for (int i = 0; i < 15; i++) {
            testHello();
        }
    }

    private static void testHello() {
        try {
            SphU.entry(KEY);
            System.out.println("Hello");
        } catch (BlockException e) {
            System.out.println("Blockd!");
        }
    }

    /**
     * 加载规则
     */
    private static void initRules() {
        ReadableDataSource<String, List<FlowRule>> dataSource = new NacosDataSource<>(remoteAddress, groupId, dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));

        FlowRuleManager.register2Property(dataSource.getProperty());
    }

}
